package com.offcn.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
            1、确认当前访问的到底是哪一个Servlet对象，并且要拿到该Servlet的字节码对象！
            2、获取到要执行的方法名称，通过反射调用类中的方法执行代码！
         */
        Class<? extends BaseServlet> clazz = this.getClass();
        //获取页面发送请求时传递的方法名
        String func = request.getParameter("func");
        try {
            //字节码对象，调用获取类中方法的方法
            Method method = clazz.getDeclaredMethod(func, HttpServletRequest.class, HttpServletResponse.class);
            //打通私有方法的访问权限
            method.setAccessible(true);
            //执行方法
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
